<?php
namespace app\api\controller;

use app\common\model\GoodsDoctorComment;
use app\common\model\User;
use app\common\controller\ApiBase;
use think\Request;
use think\Db;

class DoctorComment extends Controller
{
    /**
     * 提交医生评价
     */
    public function submit()
    {
        $data = $this->request->post();
        $user = $this->getUser();
    
        if (empty($data['order_id']) || empty($data['score'])) {
            return $this->renderError('参数缺失');
        }
        // 查询订单获取对应的医生ID（goods_id）
        $orderGoods = Db::name('order_goods')
            ->where('order_id', $data['order_id'])
            ->find();

        if (!$orderGoods) {
            return $this->renderError('订单信息不存在');
        }
        // 判断是否已评价过
        $exists = Db::name('goods_doctor_comment')
            ->where([
                'order_id' => $data['order_id'],
                'user_id'  => $user['user_id']
            ])
            ->find();

        if ($exists) {
            return $this->renderError('您已评价过该订单，无法重复评价');
        }
        // 根据 order_id 查找订单商品中的 goods_id
        $orderGoods = Db::name('order_goods')->where('order_id', $data['order_id'])->find();
        if (!$orderGoods) {
            return $this->renderError('未找到对应的订单商品');
        }
    
        $comment = new GoodsDoctorComment();
        $result = $comment->save([
            'goods_id'     => $orderGoods['goods_id'],
            'user_id'      => $user['user_id'],
            'order_id'     => $data['order_id'],
            'score'        => $data['score'],
            'content'      => $data['content'] ?? '',
            'images'       => isset($data['images']) ? json_encode($data['images'], JSON_UNESCAPED_UNICODE) : '',
            'is_anonymous' => $data['is_anonymous'] ?? 0,
            'tags'         => isset($data['tags']) ? json_encode($data['tags'], JSON_UNESCAPED_UNICODE) : '',
            'wxapp_id'     => $data['wxapp_id'] ?? 10001,
            'create_time'  => date('Y-m-d H:i:s') // 记录创建时间
        ]);
    
        if (!$result) {
            return $this->renderError('评价失败');
        }
    
        return $this->renderSuccess([], '评价提交成功');
    }
        /**
     * 获取医生评价列表（分页）
     */
    public function list()
    {
        $goodsId = input('goods_id/d', 0);
        $page = input('page/d', 1);
        $listRows = input('pageSite/d', 10);
        if ($goodsId <= 0) {
            return $this->renderError('缺少医生ID');
        }

        $query = GoodsDoctorComment::where('goods_id', $goodsId)
            ->where('is_show', 1)
            ->order('create_time desc');

        $list = $query->paginate($listRows, false, [
            'page' => $page,
            'query' => request()->param()
        ]);
        $list->each(function (&$item) {
            $item['images'] = json_decode($item['images'], true);
            $item['tags'] = json_decode($item['tags'], true);
            if ($item['is_anonymous']) {
                $item['user_name'] = '匿名用户';
            } else {
                $user = Db::name('user')->where('user_id', $item['user_id'])->find();
                $item['user_name'] = $user['nickName'] ?? '未知用户';
            }
        });
        // dump($list);die;
        return $this->renderSuccess(compact('list'));
    }
}